"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 兼容M*数据库date类型
Case Name   : 默认兼容A类型数据库下，插入date类型的整数，合理报错
Create At   : 2023.08.09
Owner       : z@wan005
Description :
    1、创建数据库
    2、连接兼容a库建表，date类型插入整数转换
    3、清理环境
Expect      :
    1、成功
    2、建表成功，插入数据报错
    3、成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class CompatibilityTest034(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.db_name = "db_date_0034"
        self.tb_name = "tb_date_0034"

    def test_atan(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '-----step1:创建数据库 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop database if exists {self.db_name};" \
                     f"create database {self.db_name} dbcompatibility 'A';"
        msg = self.sh_primary.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn('CREATE DATABASE', msg, '执行失败:' + text)

        text = '-----step2:连接兼容a库建表，date类型插入整数转换 ' \
               'expect:建表成功，插入数据报错---'
        self.log.info(text)
        sql_cmd = f"create  table {self.tb_name} (c1 date);" \
                  f"insert into {self.tb_name} values(20220201::date);" \
                  f"insert into {self.tb_name} values(cast(20220201 as date));"
        msg = self.sh_primary.execut_db_sql(sql_cmd,
                                            dbname=self.db_name)
        self.log.info(msg)
        self.assertIn('CREATE TABLE', msg, '执行失败:' + text)
        self.assertEqual(2, msg.count(
            'ERROR:  cannot cast type integer to timestamp without time zone'),
                         '执行失败:' + text)

    def tearDown(self):
        text = '----step3:清理环境;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.tb_name};"
        msg = self.sh_primary.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(msg)
        self.assertIn('DROP DATABASE', msg, '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
